<template>
  <div class="bind-email-container">
    <el-input v-model="email" size="small" placeholder="请输入所要绑定的邮箱" />
    <el-input v-model="emailCode" size="small" placeholder="请输入邮箱验证码">
      <template slot="append">
        <span v-if="isSend">{{ countdown }}秒后可发送</span>
        <a v-else @click="sendEmail">发送验证码</a>
      </template>
    </el-input>
    <el-button size="mini" type="primary" @click="bindSuperUserEmail">确认绑定</el-button>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { saveSuperUserEmail } from '@/api/super_user'
import { sendEmail } from '@/api/Info_verify'
import { validEmail } from '@/utils/validate'
export default {
  name: 'BindEmail',
  components: {},
  props: {},
  data () {
    return {
      email: '',
      emailCode: '',
      isSend: false,
      countdown: 60,
      timer: null
    }
  },
  computed: { ...mapGetters(['SUPER_USER_INFO']) },
  watch: {},
  created () {},
  mounted () {},
  beforeDestroy () {
    clearInterval(this.timer)
  },
  methods: {
    // 绑定邮箱
    bindSuperUserEmail: async function () {
      if (!this.email) return this.$message({ message: '请先输入要绑定的邮箱!', type: 'error', duration: 1000 })
      if (!this.emailCode) return this.$message({ message: '请先输入验证码!', type: 'error', duration: 1000 })
      if (!validEmail(this.email)) return this.$message({ message: '非法的邮箱格式!', type: 'error', duration: 1000 })
      const data = {
        id: this.SUPER_USER_INFO.id,
        username: this.SUPER_USER_INFO.username,
        email: this.email,
        code: this.emailCode
      }
      const res = await saveSuperUserEmail(data)
      if (!res) return this.$message({ message: '没有改动!', type: 'error', duration: 1000 })
      this.$message({ message: '绑定成功', type: 'success', duration: 1000 })
      this.$emit('reset-data')
    },
    // 发送邮箱验证码
    sendEmail: async function () {
      if (!this.email) return this.$message({ message: '请先输入要绑定的邮箱!', type: 'error', duration: 1000 })
      if (!validEmail(this.email)) return this.$message({ message: '非法的邮箱格式!', type: 'error', duration: 1000 })
      const data = {
        'username': this.SUPER_USER_INFO.username,
        'email': this.email
      }
      const res = await sendEmail(data)
      if (res) {
        this.isSend = true
        this.openCountdown()
      }
    },
    // 开启倒计时
    openCountdown: function () {
      this.timer = setInterval(() => {
        if (this.countdown < 1) {
          clearInterval(this.timer)
          this.isSend = false
          this.countdown = 60
        }
        this.countdown--
      }, 1000)
    }
  }
}
</script>

<style scoped lang="scss">
.bind-email-container {
  .el-input {
    margin-bottom: 20px;
  }
  .el-button {
    width: 100%;
  }
  a {
    &:hover {
      color: #007fff;
    }
  }
}
</style>
